from django import forms
from django.core.validators import RegexValidator, MinLengthValidator, MaxLengthValidator
from BloodSpiderAPI import models
from django.db.models import Q
import time
import decimal
from BloodSpiderAPI.apis.order_v2 import utils as order_v2_utils


# OrderListV2表单验证
class OrderListV2Form(forms.ModelForm):
    """OrderListV2模型的表单验证类"""
    # 定义各个字段的验证规则
    dailiantong_order_id = forms.CharField(max_length=255, required=False)
    dailianwangzi_order_id = forms.CharField(max_length=255, required=False)
    order_name = forms.CharField(max_length=255, required=False)
    receiving_price = forms.DecimalField(max_digits=10, decimal_places=2, required=False, min_value=0)
    receiving_margin = forms.DecimalField(max_digits=10, decimal_places=2, required=False, min_value=0)
    receiving_efficiency_fee = forms.DecimalField(max_digits=10, decimal_places=2, required=False, min_value=0)
    receiving_delivery_time = forms.CharField(max_length=255, required=False)
    receiving_server = forms.CharField(max_length=255, required=False)
    posting_price = forms.DecimalField(max_digits=10, decimal_places=2, required=False, min_value=0)
    posting_security_fee = forms.DecimalField(max_digits=10, decimal_places=2, required=False, min_value=0)
    posting_efficiency_fee = forms.DecimalField(max_digits=10, decimal_places=2, required=False, min_value=0)
    completed_profit = forms.DecimalField(max_digits=10, decimal_places=2, required=False)
    uncompleted_profit = forms.DecimalField(max_digits=10, decimal_places=2, required=False)
    status = forms.IntegerField(required=False, min_value=1, max_value=12)
    character_name = forms.CharField(max_length=255, required=False)
    account_owner = forms.CharField(max_length=255, required=False)
    account_password = forms.CharField(max_length=255, required=False)
    owner_phone = forms.CharField(max_length=20, required=False)
    remark = forms.CharField(max_length=255, required=False)
    
    class Meta:
        model = models.OrderListV2
        fields = [
            'dailiantong_order_id', 'dailianwangzi_order_id', 'order_name', 'receiving_price', 'receiving_margin',
            'receiving_efficiency_fee', 'receiving_delivery_time', 'receiving_server',
            'posting_price', 'posting_security_fee', 'posting_efficiency_fee',
            'completed_profit', 'uncompleted_profit', 'status',
            'character_name', 'account_owner', 'account_password', 'owner_phone', 'remark'
        ]


# 创建OrderListV2订单API
def create_order_v2(request):
    """创建新的OrderListV2订单
    
    Args:
        request: Django请求对象
        
    Returns:
        JsonResponse: 包含创建结果的JSON响应
    """
    if request.method != 'POST':
        return order_v2_utils.response_dict(message="请使用POST请求", code=1)
    
    try:
        # 创建订单对象
        order_data = {}
        
        # 只处理传入的字段，未传入的使用默认值
        for field in OrderListV2Form.Meta.fields:
            if field in request.POST and request.POST.get(field):
                # 处理DecimalField类型字段
                if field in ['receiving_price', 'receiving_margin', 'receiving_efficiency_fee',
                            'posting_price', 'posting_security_fee', 'posting_efficiency_fee',
                            'completed_profit', 'uncompleted_profit']:
                    try:
                        order_data[field] = decimal.Decimal(request.POST.get(field))
                    except decimal.InvalidOperation:
                        return order_v2_utils.response_dict(message=f"{field}格式无效", code=1)
                # 处理IntegerField类型字段
                elif field == 'status':
                    try:
                        status_value = int(request.POST.get(field))
                        # 验证状态值是否在有效范围内
                        valid_statuses = [choice[0] for choice in models.OrderListV2.STATUS_CHOICES]
                        if status_value in valid_statuses:
                            order_data[field] = status_value
                        else:
                            return order_v2_utils.response_dict(message="订单状态值无效", code=1)
                    except ValueError:
                        return order_v2_utils.response_dict(message="订单状态必须是数字", code=1)
                # 处理其他字段
                else:
                    order_data[field] = request.POST.get(field)
        
        # 创建订单
        order = models.OrderListV2.objects.create(**order_data)
        
        # 转换为字典并返回
        response_data = order_v2_utils.utils_model_to_dict(order)
        return order_v2_utils.response_dict(data=response_data, message="订单创建成功")
    except Exception as e:
        return order_v2_utils.response_dict(message=f"创建失败: {str(e)}", code=1)


# 获取OrderListV2订单详情API
def get_order_v2(request):
    """获取OrderListV2订单详情
    
    Args:
        request: Django请求对象
        
    Returns:
        JsonResponse: 包含订单详情的JSON响应
    
    说明：
        支持通过order_id、代练通ID或代练丸子ID三种方式查询订单
    """
    if request.method != 'GET':
        return order_v2_utils.response_dict(message="请使用GET请求", code=1)
    
    order_id = request.GET.get('order_id')
    if not order_id:
        return order_v2_utils.response_dict(message="缺少订单ID参数", code=1)
    
    try:
        # 构建查询条件，支持通过order_id、代练通ID或代练丸子ID进行匹配
        from django.db.models import Q
        import uuid
        
        # 检查order_id是否为有效的UUID格式
        try:
            uuid.UUID(order_id)
            is_uuid = True
        except ValueError:
            is_uuid = False
        
        # 根据是否为UUID格式构建不同的查询条件
        if is_uuid:
            # 是UUID格式，使用完整的查询条件
            order = models.OrderListV2.objects.get(
                Q(order_id=order_id) | 
                Q(dailiantong_order_id=order_id) | 
                Q(dailianwangzi_order_id=order_id)
            )
        else:
            # 不是UUID格式，只使用非UUID字段进行查询
            order = models.OrderListV2.objects.get(
                Q(dailiantong_order_id=order_id) | 
                Q(dailianwangzi_order_id=order_id)
            )
        response_data = order_v2_utils.utils_model_to_dict(order)
        return order_v2_utils.response_dict(data=response_data, message="获取成功")
    except models.OrderListV2.DoesNotExist:
        return order_v2_utils.response_dict(message="订单不存在", code=1)
    except Exception as e:
        return order_v2_utils.response_dict(message=f"获取失败: {str(e)}", code=1)


# 更新OrderListV2订单API
def update_order_v2(request):
    """更新OrderListV2订单，只更新传入的字段
    
    Args:
        request: Django请求对象
        
    Returns:
        JsonResponse: 包含更新结果的JSON响应
        
    说明：
        支持通过order_id、代练通ID或代练丸子ID三种方式匹配订单
    """
    if request.method != 'POST':
        return order_v2_utils.response_dict(message="请使用POST请求", code=1)
    
    order_id = request.POST.get('order_id')
    if not order_id:
        return order_v2_utils.response_dict(message="缺少订单ID参数", code=1)
    
    try:
        # 构建查询条件，支持通过order_id、代练通ID或代练丸子ID进行匹配
        from django.db.models import Q
        import uuid
        
        # 检查order_id是否为有效的UUID格式
        try:
            uuid.UUID(order_id)
            is_uuid = True
        except ValueError:
            is_uuid = False
        
        # 根据是否为UUID格式构建不同的查询条件
        if is_uuid:
            # 是UUID格式，使用完整的查询条件
            order = models.OrderListV2.objects.get(
                Q(order_id=order_id) | 
                Q(dailiantong_order_id=order_id) | 
                Q(dailianwangzi_order_id=order_id)
            )
        else:
            # 不是UUID格式，只使用非UUID字段进行查询
            order = models.OrderListV2.objects.get(
                Q(dailiantong_order_id=order_id) | 
                Q(dailianwangzi_order_id=order_id)
            )
        update_data = {}
        
        # 只处理传入的字段，未传入的保持不变
        for field in OrderListV2Form.Meta.fields:
            if field in request.POST and request.POST.get(field) is not None:
                # 处理DecimalField类型字段
                if field in ['receiving_price', 'receiving_margin', 'receiving_efficiency_fee',
                            'posting_price', 'posting_security_fee', 'posting_efficiency_fee',
                            'completed_profit', 'uncompleted_profit']:
                    try:
                        update_data[field] = decimal.Decimal(request.POST.get(field))
                    except decimal.InvalidOperation:
                        return order_v2_utils.response_dict(message=f"{field}格式无效", code=1)
                # 处理IntegerField类型字段
                elif field == 'status':
                    try:
                        status_value = int(request.POST.get(field))
                        # 验证状态值是否在有效范围内
                        valid_statuses = [choice[0] for choice in models.OrderListV2.STATUS_CHOICES]
                        if status_value in valid_statuses:
                            update_data[field] = status_value
                        else:
                            return order_v2_utils.response_dict(message="订单状态值无效", code=1)
                    except ValueError:
                        return order_v2_utils.response_dict(message="订单状态必须是数字", code=1)
                # 处理其他字段
                else:
                    update_data[field] = request.POST.get(field)
        
        # 如果没有任何可更新字段
        if not update_data:
            return order_v2_utils.response_dict(message="没有提供可更新字段", code=1)
        
        # 更新订单
        for key, value in update_data.items():
            setattr(order, key, value)
        order.save()
        
        # 返回更新后的订单数据
        response_data = order_v2_utils.utils_model_to_dict(order)
        return order_v2_utils.response_dict(data=response_data, message="订单更新成功")
    except models.OrderListV2.DoesNotExist:
        return order_v2_utils.response_dict(message="订单不存在", code=1)
    except Exception as e:
        return order_v2_utils.response_dict(message=f"更新失败: {str(e)}", code=1)


# 删除OrderListV2订单API
def delete_order_v2(request):
    """删除OrderListV2订单
    
    Args:
        request: Django请求对象
        
    Returns:
        JsonResponse: 包含删除结果的JSON响应
        
    说明：
        支持通过order_id、代练通ID或代练丸子ID三种方式匹配订单
    """
    if request.method != 'POST':
        return order_v2_utils.response_dict(message="请使用POST请求", code=1)
    
    order_id = request.POST.get('order_id')
    if not order_id:
        return order_v2_utils.response_dict(message="缺少订单ID参数", code=1)
    
    try:
        # 构建查询条件，支持通过order_id、代练通ID或代练丸子ID进行匹配
        from django.db.models import Q
        import uuid
        
        # 检查order_id是否为有效的UUID格式
        try:
            uuid.UUID(order_id)
            is_uuid = True
        except ValueError:
            is_uuid = False
        
        # 根据是否为UUID格式构建不同的查询条件
        if is_uuid:
            # 是UUID格式，使用完整的查询条件
            order = models.OrderListV2.objects.get(
                Q(order_id=order_id) | 
                Q(dailiantong_order_id=order_id) | 
                Q(dailianwangzi_order_id=order_id)
            )
        else:
            # 不是UUID格式，只使用非UUID字段进行查询
            order = models.OrderListV2.objects.get(
                Q(dailiantong_order_id=order_id) | 
                Q(dailianwangzi_order_id=order_id)
            )
        order.delete()
        return order_v2_utils.response_dict(message="订单删除成功")
    except models.OrderListV2.DoesNotExist:
        return order_v2_utils.response_dict(message="订单不存在", code=1)
    except Exception as e:
        return order_v2_utils.response_dict(message=f"删除失败: {str(e)}", code=1)


# 获取OrderListV2订单列表API
def get_order_v2_list(request):
    """获取OrderListV2订单列表，可以根据条件筛选
    
    Args:
        request: Django请求对象
        
    Returns:
        JsonResponse: 包含订单列表的JSON响应
    """
    if request.method != 'GET':
        return order_v2_utils.response_dict(message="请使用GET请求", code=1)
    
    try:
        # 获取查询参数
        status = request.GET.get('status')
        keyword = request.GET.get('keyword')
        page = int(request.GET.get('page', 1))
        page_size = int(request.GET.get('page_size', 10))
        
        # 构建查询
        query = Q()
        
        # 按状态筛选
        if status:
            try:
                status_value = int(status)
                query &= Q(status=status_value)
            except ValueError:
                pass
        
        # 按关键词搜索（订单名称、代练通订单ID、代练丸子订单ID、角色名、备注等）
        if keyword:
            search_fields = Q()
            search_fields |= Q(order_name__icontains=keyword)
            search_fields |= Q(dailiantong_order_id__icontains=keyword)
            search_fields |= Q(dailianwangzi_order_id__icontains=keyword)
            search_fields |= Q(character_name__icontains=keyword)
            search_fields |= Q(account_owner__icontains=keyword)
            search_fields |= Q(owner_phone__icontains=keyword)
            search_fields |= Q(remark__icontains=keyword)
            query &= search_fields
        
        # 执行查询并分页
        orders = models.OrderListV2.objects.filter(query).order_by('-create_time')
        total = orders.count()
        
        # 计算分页
        start = (page - 1) * page_size
        end = start + page_size
        order_list = orders[start:end]
        
        # 转换为字典列表
        order_data = [order_v2_utils.utils_model_to_dict(order) for order in order_list]
        
        # 构建返回数据
        response_data = {
            'total': total,
            'page': page,
            'page_size': page_size,
            'list': order_data
        }
        
        return order_v2_utils.response_dict(data=response_data, message="获取成功")
    except Exception as e:
        return order_v2_utils.response_dict(message=f"获取失败: {str(e)}", code=1)
